// pages/index/index.js
import api from '../../utils/api.js'
import { HTTP } from '../../utils/http.js'
let http = new HTTP()
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
import { config } from '../../utils/config'
import wx_authorize from '../../utils/wx-authorize.js'
import utils from '../../utils/util.js'

var app = getApp();
var qqmapsdk;

Page({
    /**
     * 页面的初始数据
     */
    data: {
        statusBarHeight: app.globalData.statusBarHeight + 45,  //取出statusBarHeight值
        showThis: false,
        // 此页面 页面内容距最顶部的距离
        height: app.globalData.height * 2 + 20,
        windowHeight: app.globalData.windowHeight,
        white: app.globalData.white,
        tabs: [
            { id: 22, name: "减肥", pid: 6 },
            { id: 8, name: "下酒菜", pid: 100 },
            { id: 49, name: "哺乳期", pid: 3 },
            { id: 45, name: "孕妇", pid: 3 },
            { id: 101, name: "斋饭", pid: 6 },
            { id: 23, name: "胃病", pid: 7 },
            { id: 44, name: "小白", pid: 3 },
            { id: 41, name: "烘焙", pid: 4 },
            { id: 16, name: "熬夜失眠", pid: 7 },
        ],
        list: [],
        show: false,
        show1: false,
        current: 0,
        current1: 0,
        num: "", //已选菜谱的数量
        page: 1, //页码
        pagesize: 8, //每页展示数量
        size: 10, //每页展示的留言条数
        address: "", //当前地址信息
        over: false, //数据是否请求完
        has: true, //附近是否有商家
        none: false, //有没有菜(有商家)
        scrollId: "I0", //定位标签的id
        globalData: {}, // 保存屏幕的宽高
        zhuantiList: [],
        bannerShow: true, //是否展示banner
        all: true,
        imgUrl: "",
        show2: false,
        hide_good_box: true, // 抛物线动画
        loadingShow: false,
        showModel: false, // 模态窗口
        showDetail: false, //好友 绑定成功展示
        is_auth: false,
        address: "选择位置",
        aLength: 0,
        imgUrl: config.imgUrl,
        chefLists: [
            { id: 1, url: config.imgUrl + "/images/index/chef1.gif", avatarUrl: "https://images.weigeee.com/20190802/973b0eb5d6553cac81b590c687ff3663.png", name: "假爱厨房", view: "味歌首席美食评论家" },
            { id: 2, url: config.imgUrl + "/images/index/chef3.gif", avatarUrl: "https://images.weigeee.com/20190802/6175b0884e8eb8e3ef1becf2a4546599.png", name: "厨师王刚", view: "宽油美食代言人" },
        ],
        noticeList: [{
            content0: "成为味歌会员，可享受多重福利、优惠。",
            url: '/pages/vippromotion/vippromotion'
        },
        {
            content0: "味歌-推广版，特别说明。",
            url: '/pages/member-infoCenter/member-infoCenter'
        },
        ],
        bannerList: [], // 轮播图列表
        hotInfo: "", // 热点头条
        defaultBool: 0,
        noRefresh: false,
        group_list: [], // 拼团列表
        tejia_list: [], // 特价列表
    },
    onMyEvent: function (e) {
        //通过事件接收
        this.setData({
            num: e.detail.num
        })
    },
    //授权 初始化
    likesClick(e) {
        this.setData({
            is_auth: true
        })
    },
    // 登录的一系列逻辑
    login() {
        var that = this
        if (wx.getStorageSync("address")) {
        } else { // 获取当前位置 
            let qqmapsdk = new QQMapWX({
                key: "OI5BZ-G3FWJ-A6VFG-FGA5U-AZHAT-2NBVY"
            });
            // 唤起获取地理位置授权
            app.getUserLocation(function () {
                wx.getLocation({
                    type: 'wgs84',
                    success: (res) => {
                        // 获取精确的地理位置
                        qqmapsdk.reverseGeocoder({
                            //获取输入框值并设置keyword参数
                            location: {
                                latitude: res.latitude,
                                longitude: res.longitude
                            },
                            success: (res) => { //搜索成功后的回调
                                var address = {
                                    address: res.result.address_component.street,
                                    title: res.result.address_component.street,
                                    id: res.result.address_reference.street.id,
                                    addr: res.result.address,
                                    city: res.result.address_component.city,
                                    district: res.result.address_component.district,
                                    province: res.result.address_component.province,
                                    latitude: res.result.location.lat,
                                    longitude: res.result.location.lng,

                                }
                                wx.setStorageSync("address", address)
                                that.setData({
                                    address: res.result.address_component.street
                                });
                                wx.setStorageSync('city_name', res.result.address_component.city)
                            }
                        });
                    },
                    fail: (err) => {
                        wx.hideLoading();
                    }
                })

            });
        }



    },
    //接口
    //获取附近商家的所有菜谱列表接口
    shopAllCookBooks(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.shopAllCookBook,
                data: obj,
                success: res => {
                    if (res.data.data) {
                        res.data.data.map(item => {
                            item.type = 0
                        })
                        resolve(res.data.data)
                    }

                }
            })
        })
    },


    /**/
    searchTip() {
        if (this.data.inputValue) {
            this.setData({
                searchTip: true
            })
        } else {
            this.setData({
                searchTip: !this.data.searchTip
            })
        }

    },
    /*搜索失去焦点*/
    inputBlur() {
        if (this.data.inputValue) {
            this.setData({
                searchTip: true
            })
        } else {
            this.setData({
                searchTip: !this.data.searchTip
            })
        }
    },
    /*搜索*/
    searchInput: utils.debounce(function (e) {
        let inputValue = e[0].detail.value;

        if (inputValue) {
            this.setData({
                inputValue,
                deleteBtn: true
            })
        }

    }, 200),
    /*删除搜索框内容*/
    deleteSearch() {
        this.setData({
            inputValue: '',
            deleteBtn: false
        })
    },
    /*搜索按钮*/
    searchHandle() {
        this.setData({
            searchTip: true
        })
        if (this.data.inputValue == '') {
            wx.showToast({
                title: '请输入菜品名称',
                icon: 'none',
                duration: 1500
            })
            return;
        }
    },

    // //获得联合专题列表
    getProjectListTowNew(obj) {
        return new Promise((resolve, reject) => {
            http.request({
                url: api.getPListTowNew,
                data: obj,
                success: res => {
                    var project = res.data
                    project.map(item => {
                        item.type = 1
                    })
                    if (project.length != 0) {
                        this.getCollectStatus({
                            userId: wx.getStorageSync("user_id"),
                            productId: project[0].id
                        }).then(res => {
                            if (res.message == "商品已经收藏了") {
                                project[0].flag = true
                                resolve(project)
                            } else {
                                project[0].flag = false
                                resolve(project)
                            }
                        })
                    } else {
                        resolve([])
                    }
                }
            })
        })
    },


    //用户对专题添加或取消收藏专题接口
    addDelCollectProject(obj) {
        http.request({
            url: api.addDelCollectProject,
            data: obj,
            success: res => { }
        })
    },

    getInfo(obj, url) {
        return new Promise((resolve, reject) => {
            http.request({
                url: url,
                data: obj,
                success: res => {
                    resolve(res);
                }
            })
        })
    },
    //页面跳转
    toMessage() { // 跳转留言页面
        wx.navigateTo({
            url: '/pages/message/message',
        })
    },
    dizhi() { // 跳转全部地址页面
        wx.navigateTo({
            url: '/pages/allDizhi/allDizhi?order=1',
        })
    },
    getDizhi() { // 跳转切换地址页面
        wx.navigateTo({
            url: "/pages/getDizhi/getDizhi?order=0"
        });
    },
    getDizhi1() { // 跳转切换地址页面
        wx.navigateTo({
            url: "/pages/getDizhi/getDizhi?order=2"
        });
    },
    toSearch() { // 跳转搜索页面
        wx.navigateTo({
            url: "/pages/search/search"
        })
    },
    //地址
    getAddressLength(id) {
        http.request({
            url: api.allAddress,
            method: "POST",
            data: {
                user_id: wx.getStorageSync("user_id")
            },
            success: (res) => {
                if (res.data.length == 0) {
                    wx.navigateTo({
                        url: "/pages/addDizhi/addDizhi"
                    })
                } else {
                    wx.navigateTo({
                        url: "/pages/video/video?id=" + id
                    })
                }
            }
        })
    },
    goBack() {
        this.setData({
            showThis: false
        })
    },
    viewDite(e) {
        let id = e.currentTarget.dataset.id;
        let pid = e.currentTarget.dataset.pid
        wx.navigateTo({
            url: '/pages/classify/diet/diet?id=' + id + '&pid=' + pid
        })
    },
    getCookList(id, healthCook) {
        let that = this
        let address = wx.getStorageSync('address');
        let data = {}
        if (!address) {
            data = {
                lat: '30.49984',
                lng: '114.34253',
                id: id,
                page: 1
            }
        } else {
            data = {
                lat: address.latitude,
                lng: address.longitude,
                id: id,
                page: 1
            }
        }

        utils.getInfo(api.shopCateCookBooks, "GET", data, false).then(res => {
            that.setData({
                [healthCook]: res.data
            })
        })
    },

    toVideo(e) { // 去菜谱详情页面

        let address = wx.getStorageSync('address');
        if (!address) {
            this.login();
            return;
        }

        var id = e.currentTarget.dataset.id
        if (wx.getStorageInfoSync("user_id")) {
            wx.navigateTo({
                url: "/pages/video/video?id=" + id
            })
        } else {
            this.getAddressLength(id)
        }



    },
    change() { // 更改地址按钮
        wx.navigateTo({
            url: '/pages/allDizhi/allDizhi?order=1',
        })
    },
    toMain(e) { // 跳转已选菜谱页面
        if (this.data.num == 0) {
            wx.showToast({
                title: '您还未选菜',
                icon: "none"
            })
        } else {
            wx.navigateTo({
                url: "/pages/recommendShopList/recommendShopList?type=1"
            })
        }
    },

    //获取已选菜单的num值
    count() {
        var newList = wx.getStorageSync("select-menus") || []
        newList.filter((item) => {
            return item.num
        })
        var count = 0
        newList.map((item) => {
            count += item.num
        })
        this.setData({
            num: count
        })
    },
    //点击专题的关注按钮
    attention(e) {
        var list = this.data.list
        var project = list.filter(item => {
            return item.id == e.target.dataset.id
        })[0]
        let obj = {
            userId: wx.getStorageSync("user_id"),
            productId: e.target.dataset.id
        }
        if (project.flag) {
            obj.statusID = 2;
            this.addDelCollectProject(obj);
            wx.showToast({
                title: '取消关注',
                icon: "none",
                duration: 1500
            })

        } else {
            obj.statusID = 1;
            this.addDelCollectProject(obj);
            wx.showToast({
                title: '关注成功',
                duration: 1500
            })
        }
        project.flag = !project.flag
        this.setData({
            list
        })
    },

    //关闭按钮
    close() {
        wx.showTabBar({})
        this.setData({
            status: 0
        })
    },
    open() {
        this.setData({
            show2: true
        })
    },
    //确定使用当前定位
    sure() {
        wx.showTabBar({})
        var city = wx.getStorageSync("city") || ""
        // if (!city) {
        //     this.getAddUserCityId({
        //         id: wx.getStorageSync("user_id"),
        //         name: wx.getStorageSync("address").city
        //     }).then(res => {
        //         wx.setStorageSync("city", {
        //             id: res.city_id,
        //             name: wx.getStorageSync("address").city
        //         })
        //     })
        // }
        var that = this;
        let qqmapsdk = new QQMapWX({
            key: "OI5BZ-G3FWJ-A6VFG-FGA5U-AZHAT-2NBVY"
        });

        this.setData({
            have: 1,
            show2: false
        })
    },
    //确认地址按钮
    confirm() {
        var dizhi = this.data.allDizhi[this.data.current1]
        var address = {
            id: dizhi.community_id,
            address: dizhi.address,
            detail: dizhi.detail,
            name: dizhi.name,
            phone: dizhi.mobile,
            latitude: dizhi.lat,
            longitude: dizhi.lon,
        }
        wx.setStorageSync("address", address)
        app.globalData.pass = true
        wx.showTabBar({})
        this.setData({
            address: address.address,
            show1: false
        })
    },
    swiperChange(e) {
        this.setData({
            current1: e.detail.current
        })
    },
    // 点击更多按钮
    more() {
        wx.navigateTo({
            url: "/pages/menu-classify/menu-classify?id=0"
        })
    },
    // 跳转专题页面
    toProject(e) {
        wx.navigateTo({
            url: '/pages/project/project?id=' + e.target.dataset.id,
        })
    },
    // 点击切换分类
    changeIndex(e) {
        wx.navigateTo({
            url: "/pages/menu-classify/menu-classify?id=" + e.currentTarget.dataset.idx
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //调取订阅消息
        wx_authorize.subcriptionAuthorizeCheck(app.globalData.tmplIds)
        this.login() // 登录的一系列逻辑
        // this.getCarElementSite(); // 获取 菜单图标的位置
        var that = this;
        let signShare = wx.getStorageSync('signShare') || true; //分享只做一次绑定关系
        //========================分享跳转操作=================================
        // 分享参数 
        var GoTo = options.GoTo;
        if (GoTo) {
            console.log('GoTo', decodeURIComponent(GoTo))
            wx.navigateTo({
                url: decodeURIComponent(GoTo)
            })
            return;
        }

        if (options.typeShare == 1) {
            wx.navigateTo({
                url: `${options.redirect}?id=${options.id}`
            })
        }

        this.getCookList(89, 'healtop');
        this.getCookList(88, 'healfoot');

        //好友分享，确定绑定关系//用户是由 邀请者 分享进入首页的 
        if (wx.getStorageSync('user_id') && options.inviter_user_id && signShare) {
            wx.setStorageSync('signShare', false)
            that.setData({
                userInfo1: { //被邀请者
                    nickName: options.inviter_user_nickName,
                    avatarUrl: options.inviter_user_avatarUrl
                },
                userInfo2: { //被邀请者
                    nickName: wx.getStorageSync('nickName'),
                    avatarUrl: wx.getStorageSync('avatarUrl')
                }
            })
            //都存在，则该用户已授权小程序
            let inviter_user_id = options.inviter_user_id;
            let invitee_user_id = wx.getStorageSync('user_id'); //被邀请者的user_id
            http.request({
                url: "/Crony/userAddCrony",
                data: {
                    uid: inviter_user_id,
                    fid: invitee_user_id
                },
                success: (res) => {
                    this.showDetail()
                }
            });
        } else if (options.inviter_user_id && !wx.getStorageSync('user_id')) {
            wx.setStorageSync('signShare', false)
            that.setData({
                userInfo1: { //被邀请者
                    nickName: options.inviter_user_nickName,
                    avatarUrl: options.inviter_user_avatarUrl
                },
            })
            // 如若时新用户时
            this.setData({
                inviter_user_id: options.inviter_user_id //邀请者的id
            })
        }
        //重返当日菜谱页面时，去除已购买菜谱id
        wx.removeStorageSync('alreadyMenusId') // 已购买菜谱的id
        wx.removeStorageSync('userMenus') // 已购买的菜谱
        // this.getHotInformation({ id: wx.getStorageSync("city").id || 1, }) // 拿到味歌头条区域唯一一个热门资讯列表
        this.getTopBanner() // 获取banner图
        // this.getSlgs({ page: 1, size: this.data.size1 }) // 拿到两个时令果蔬的接口
        this.getJyqcList({ page: 1, size: 2 }) // 获得厨师列表
        // this.getListInformation({ page: 1, size: 6 })
    },
    onShow: function () {
        let is_auth = wx.getStorageSync('is_auth');
        if (is_auth) {
            this.setData({
                is_auth: true
            })
        }
        wx.wg_util.refreshShopCarBadge();
        this.setData({
            page: 1, //重置页码
            address: wx.getStorageSync("address").address, //获取当前地址信息
            over: false,
        })
        setTimeout(() => {
            this.setData({
                address: wx.getStorageSync("address").address, //获取当前地址信息
            })
        }, 1000)
        if (this.data.status == 1) {
            wx.hideTabBar({})
        }

        if (!this.data.noRefresh) {
            this.getGoods() // 获取当日菜谱列表
        }

        this.count() // 设置num
        //获取所有的地址列表
        let address = wx.getStorageSync('address')
        if (!address) {
            this.getAlladdress();
        }
        this.getGroupBuyList();
    },
    // 获取当日菜谱列表
    getGoods() {
        this.setData({
            list: []
        })
        var address = wx.getStorageSync("address")
        http.request({
            url: api.shopAllCookBooks,
            data: {
                lat: address.latitude,
                lng: address.longitude,
                // lat: 30.507510011,
                // lng:114.442770016,
                page: 1
            },
            success: (res) => {
                if (res.code == 200) { //附近有商家
                    app.globalData.has = true
                    var list = res.data.data
                    list.map(item => {
                        item.type = 0
                    })
                    this.setData({
                        list,
                        all: true,
                    })
                }
            }
        })
    },
    getAlladdress() {
        let that = this
        http.request({
            url: api.allAddress,
            method: "POST",
            data: {
                user_id: wx.getStorageSync("user_id")
            },
            success: (res) => {
                if (res.code == 200) {
                    if (res.data.length >= 2) {
                        // if (!app.globalData.pass) {
                        //   wx.hideTabBar({})
                        //   this.setData({
                        //     show1: true
                        //   })
                        // }else{
                        //   // wx.showTabBar({})
                        //   this.setData({
                        //     show1: false
                        //   })
                        // }
                    } else {
                        // wx.showTabBar({})
                        app.globalData.pass = true
                        this.setData({
                            show1: false
                        })
                        var dizhi = res.data[0]
                        if (wx.getStorageSync("address").id) {
                            if (dizhi.id != wx.getStorageSync("address").id) {
                                var address = {
                                    id: dizhi.community_id,
                                    address: dizhi.address,
                                    detail: dizhi.detail,
                                    name: dizhi.name,
                                    phone: dizhi.mobile,
                                    latitude: dizhi.lat,
                                    longitude: dizhi.lon,
                                }
                                this.setData({
                                    address: dizhi.address
                                })
                                wx.setStorageSync("address", address)
                            }
                        }
                    }

                    var list = res.data
                    var index1 = 0
                    list.filter((item, index) => {
                        if (item.id == wx.getStorageSync("address").id) {
                            index1 = index
                        }
                    })
                    list[0] = list.splice(index1, 1, list[0])[0];
                    this.setData({
                        allDizhi: list,
                    })
                } else {
                    this.setData({
                        allDizhi: [],
                    })
                }
            }
        });
    },

    onHide: function () {

    },
    onReachBottom: function () {
        var page = this.data.page + 1 //页码加一
        if (wx.getStorageSync("search-list")) { } else {
            var address = wx.getStorageSync("address")
            if (this.data.has) { //判断附近是否有商家
                if (this.data.current == 0) { //判断是否全部按钮
                    this.setData({
                        loadingShow: true
                    })
                    this.shopAllCookBooks({
                        lat: address.latitude,
                        lng: address.longitude,
                        page,
                    }).then(res => {
                        // return res
                        var list = this.data.list
                        if (res) {
                            list = list.concat(res)
                        }
                        this.setData({
                            list,
                            page,
                            loadingShow: false
                        })
                    })

                }
            }
        }

    },

    close1(e) {
        this.setData({
            showDetail: false,
            showModel: false
        })
        // wx.showTabBar({})
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    //显示厨师详情
    swiperChange: function (e) {
        this.setData({
            defaultBool: e.detail.current
        })
    },
    // 接口
    // 拿到味歌头条区域唯一一个热门资讯列表的接口
    getHotInformation(obj) {
        http.request({
            url: api.getHotInformation,
            data: obj,
            success: res => {
                this.setData({
                    hotInfo: res.data
                })
            }
        })
    },
    // 获取首页轮播图的接口
    getTopBanner() {
        http.request({
            url: api.getTopBanner,
            data: {
                id: 1
            },
            success: res => {
                this.setData({
                    bannerList: res.banner
                })
            }
        })
    },
    // 获取到拼团列表
    getGroupBuyList() {
        let address = wx.getStorageSync("address")
        let _that = this;
        http.request({
            url: api.groupList,
            data: {
                lat: address.latitude,
                lng: address.longitude,
            },
            method: "get",
            success: function (res) {
                let group_list = [];
                let tejia_list = [];
                if (res.code == 200 && res.data.data) {
                    tejia_list = res.data.data
                }
                // 拼团只取两个即可
                let count = 0;
                tejia_list.forEach(element => {
                    if (count++ < 2) {
                        group_list.push(element);
                    }
                });
                _that.setData({ group_list, tejia_list })
                console.log({ group_list, tejia_list })
            }
        })
    },

    // 拿到两个时令果蔬的接口
    // getSlgs(obj) {
    //     http.request({
    //         url: api.getSlgs,
    //         data: obj,
    //         success: res => {
    //             this.setData({
    //                 seasonal: res.data
    //             })
    //         }
    //     })
    // },
    // 获得厨师列表
    getJyqcList(obj) {
        http.request({
            url: api.getJyqcList,
            data: obj,
            success: res => {
                this.setData({
                    chefList: res.data
                })
            }
        })
    },
    // 拿到城市的资讯列表接口
    // getRangeListInformation(obj) {
    //   http.request({
    //     url: "/Information/getRangeListInformation",
    //     data: obj,
    //     success: res => {
    //       var infoList = this.data.infoList
    //       var list = infoList.concat(res.data)
    //       this.setData({
    //         infoList: list
    //       })
    //     }
    //   })
    // },
    //拿到全国资讯列表
    getListInformation(obj) {
        http.request({
            url: api.getListInformation,
            data: obj,
            success: res => {
                if (res.msg == "暂时没有全国资讯") return false
                this.setData({
                    lunboList: res.data
                })
            }
        })
    },

    toClassify() {
        wx.navigateTo({
            url: "/pages/classify/classIndex/classIndex"
        })
    },
    toHeadlines() {
        wx.navigateTo({
            url: '/pages/headlines/headlines',
        })
    },
    toHeadlinesDetail(e) {
        wx.navigateTo({
            url: "/pages/headlinesDetail/headlinesDetail?id=" + e.currentTarget.dataset.id
        })
    },
    toDetail(e) {
        wx.navigateTo({
            url: '/pages/detail/detail?id=' + e.currentTarget.dataset.id,
        })
    },
    toChef(e) {
        wx.navigateTo({
            url: '/pages/chef/chef?id=' + e.currentTarget.dataset.id,
        })
    },
    toChefMore() {
        wx.navigateTo({
            url: '/pages/chef-more/chef-more',
        })
    },
})